//
//  StatisticsViewController.m
//  OA
//
//  Created by yy on 17/6/29.
//  Copyright © 2017年 yy. All rights reserved.
//

#import "StatisticsViewController.h"
#import "CalendarView.h"
@interface StatisticsViewController ()
//控件
@property (weak, nonatomic) IBOutlet UILabel *imgL;
@property (weak, nonatomic) IBOutlet UIImageView *img;
@property (weak, nonatomic) IBOutlet UILabel *nameL;
@property (weak, nonatomic) IBOutlet UILabel *dateL;//日期
@property (weak, nonatomic) IBOutlet UILabel *weekL;//星期
@property (weak, nonatomic) IBOutlet UILabel *centerTimeL;//中心时间l
@property (weak, nonatomic) IBOutlet UIButton *lastBtn;
@property (weak, nonatomic) IBOutlet UIButton *nextBtn;

@property (weak, nonatomic) IBOutlet UIView *dayBackView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *dayBackViewLayoutConstraintWidth;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *dayBackViewLayoutConstraintHeight;

@property (weak, nonatomic) IBOutlet UILabel *workListL;//作息时间
@property (weak, nonatomic) IBOutlet UILabel *todayCardL;//今日打卡两次 工时
@property (weak, nonatomic) IBOutlet UILabel *lateTimeL;//迟到时间

@property (weak, nonatomic) IBOutlet UIImageView *imgOfType;//上班img
@property (weak, nonatomic) IBOutlet UILabel *timeLOfCardL;//上班时间
@property (weak, nonatomic) IBOutlet UILabel *typeOfCardL;//上班状态L
@property (weak, nonatomic) IBOutlet UIImageView *imgOfTypeTwo;//下班img
@property (weak, nonatomic) IBOutlet UILabel *timeLOfCardLTwo;//下班时间L
@property (weak, nonatomic) IBOutlet UILabel *typeOfCardLTwo;//下班状态L
@property (weak, nonatomic) IBOutlet UIView *ConnectedLineView;//上下班链接线
//打卡信息
@property (weak, nonatomic) IBOutlet UIView *cardView;
@property (weak, nonatomic) IBOutlet UIView *cardTwoView;
@property (weak, nonatomic) IBOutlet UILabel *zanWuXinXiL;

//________________________________________________________________________________________
@property (nonatomic,assign) float kuangao;//元素宽高

@property (nonatomic,strong) NSMutableArray *calendarCellArr;//日期号数包含上月下月的数组

@property (nonatomic,strong)StatisticsOfCalendarModel *calendarModel;
@property (nonatomic,strong)NSString * theLastChangeDateStr;//上次日期
@property (nonatomic,strong)NSString * theChangeDateStr;//当前日期

@property (nonatomic,strong)NSString *lastMonthDays;//上个月总天数
@property (nonatomic,strong)NSString *theMonthDays;//这个月总天数
@property (nonatomic,strong)NSString *oneDaysWeekStr;//这月1号的星期几
@property (nonatomic,assign)int  lastMonthDaysInOneLine; //上月占第一行的数量
@property (nonatomic,strong)NSMutableArray *arrOfDaysList;//calendarModel.statusList

@end

@implementation StatisticsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"考勤统计";
    [self initOfDataSouce];
    [self initializeUserInterface];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)initOfDataSouce{
    _kuangao = Y_mainW/7;
  
    _calendarCellArr =  [NSMutableArray array];
    for (int i = 0; i < 35; i ++) {
        [_calendarCellArr addObject:@""];
    }
    [_calendarCellArr removeAllObjects];
    for (int i = 0; i < 35; i ++) {
        [_calendarCellArr addObject:[NSString stringWithFormat:@"%d",i]];
    }
    _theChangeDateStr = _dateStr.length>0?_dateStr:[ToolOfBasic nowTime];
    _theLastChangeDateStr = _theChangeDateStr;
    [self getDataOfDate: _dateStr.length>0?_dateStr:[ToolOfBasic nowTime]];
}

- (void)getDataOfDate:(NSString*)date{
    NSMutableDictionary *parm = [NSMutableDictionary dictionary];
    [parm setObject:date forKey:@"datenumber"];
    
    [[ToolOfNetWork sharedTools]YrequestURL:oa_getStatisticsOfCalendar withParams:parm finished:^(id responsObject, NSError *error) {
        if (_Success) {
            Y_MBP_Success
            _calendarModel = [StatisticsOfCalendarModel objectWithKeyValues:responsObject[@"data"]];
            [self dataOfView];
            
        }else{
            if (![_theChangeDateStr isEqualToString:_dateStr]) {
               _theChangeDateStr = _theLastChangeDateStr;
                [self addBtns];
            }
            Y_MBP_ErrMessage
        }
    }];
}
- (void)dataOfView{
    //赋值
    _nameL.text = _calendarModel.username;
    _imgL.text = _calendarModel.username.length>2?[_calendarModel.username substringWithRange:NSMakeRange(_calendarModel.username.length-2, 2)]:_calendarModel.username;
    _dateL.text = [_calendarModel.datenumber substringToIndex:10];
    _weekL.text  = [self getWeekDayStr:_calendarModel.dateWeek];
    NSString *dateStrOfCenterL = [NSString stringWithFormat:@"%@月",[_calendarModel.datenumber substringToIndex:7]];
    _centerTimeL.text =  [dateStrOfCenterL stringByReplacingOccurrencesOfString:@"-" withString:@"年"];
    _workListL.text = _calendarModel.team;
    
    _lastMonthDays = _calendarModel.lastMonthDay;
    _theMonthDays = _calendarModel.curMonthDay;
    _oneDaysWeekStr = _calendarModel.curMonthWeek;
    _arrOfDaysList = [NSMutableArray arrayWithArray: _calendarModel.statusList];
   
    //显示
    [self statusOfDaCa];
    [self addBtns];
    
}
#pragma mark —————— 打卡显示等
- (void)statusOfDaCa{
    if ([_calendarModel.beginStatus intValue]==0&&[_calendarModel.endStatus intValue]==0) {//未打卡或者休息时间
        _cardView.hidden = YES;//暂无打卡信息
        _zanWuXinXiL.text = @"暂无打卡信息";
    }else if([_calendarModel.status intValue] != 4){
        _cardView.hidden = NO;
        
//        switch ([_calendarModel.beginStatus intValue]) {
//            case 1:
//                _imgOfType.image = Y_IMAGE(@"");
//                break;
//            case 2:
//                _imgOfType.image = Y_IMAGE(@"");
//                break;
//            case 3:
//                 _imgOfType.image = Y_IMAGE(@"");
//                break;
//                
//            default:
//                _imgOfType.hidden = YES;
//                break;
//        }
//        switch ([_calendarModel.beginStatus intValue]) {
//            case 1:
//                _imgOfTypeTwo.image = Y_IMAGE(@"");
//                break;
//            case 2:
//                _imgOfTypeTwo.image = Y_IMAGE(@"");
//                break;
//            case 3:
//                _imgOfTypeTwo.image = Y_IMAGE(@"");
//                break;
//                
//            default:
//                _imgOfTypeTwo.hidden = YES;
//                break;
//        }
        
        _timeLOfCardL.text = _calendarModel.begintime.length>0? [_calendarModel.begintime substringWithRange:NSMakeRange(11, 5)]:@"";
        _typeOfCardL.text = [self typeOfCard:_calendarModel.beginStatus];
        _lateTimeL.text = [_calendarModel.lateTime intValue]>0?[ToolOfBasic timeFormatted:[_calendarModel.lateTime intValue]]:@"";
        
        _timeLOfCardLTwo.text = _calendarModel.endtime.length>0? [_calendarModel.endtime substringWithRange:NSMakeRange(11, 5)]:@"";
        _typeOfCardLTwo.text = [self typeOfCardTwo:  _calendarModel.endStatus ];
        
        
        if (_timeLOfCardLTwo.text.length>0) {
            _ConnectedLineView.hidden = NO;
        }else{
            _ConnectedLineView.hidden = YES;
        }
    }else{
    _cardView.hidden = YES;
    _zanWuXinXiL.text = @"旷工情况";
    }
}
- (NSString *)typeOfCard:(NSString*)status{
    
    switch ([status intValue]) {
        case 0:
            return @"暂无打卡情况";
            break;
        case 1:
            return @"正常";
            break;
        case 2:
            return @"迟到";
            break;

        default:
            return @"";
            break;
    }
}

- (NSString *)typeOfCardTwo:(NSString*)status{
    
    switch ([status intValue]) {
        case 0:
            return @"暂无打卡情况";
            break;
        case 1:
            return @"正常";
            break;
        case 2:
            return @"早退";
            break;
            
        default:
            return @"";
            break;
    }
}

- (void)initializeUserInterface{
    _img.layer.cornerRadius = 15;
    _cardView.layer.borderWidth = 0.4;
    _workListL.layer.borderWidth = 0.4;
    _workListL.layer.borderColor = [[UIColor lightGrayColor]CGColor];
    _cardView.layer.borderColor = [[UIColor lightGrayColor]CGColor];
    
}
#pragma mark —————— 月份按钮
- (IBAction)lastBtnAction:(UIButton *)sender {
    [self lastMonth];
    if (_theChangeDateStr==nil || _theChangeDateStr.length==0) {
        
    }else{
    [self getDataOfDate:_theChangeDateStr];
    }
}
- (void)lastMonth{
    NSLog(@"上一个月");
    _theLastChangeDateStr = _theChangeDateStr;
    _theChangeDateStr = [ToolOfBasic dateBecomeShortStr:[ToolOfBasic dayInThePreviousMonth:[ToolOfBasic strShortBecomeDate:_theChangeDateStr]]];
    NSLog(@"%@---%@",_theChangeDateStr,_theLastChangeDateStr);
}
- (IBAction)nextBtnAction:(UIButton *)sender {
    [self nextMonth];
    if (_theChangeDateStr==nil || _theChangeDateStr.length==0) {
        
    }else{
         [self getDataOfDate:_theChangeDateStr];
    }
   
}

- (void)nextMonth{
    NSLog(@"下一个月");
    _theLastChangeDateStr = _theChangeDateStr;
    _theChangeDateStr = [ToolOfBasic dateBecomeShortStr:[ToolOfBasic dayInTheFollowingMonth:[ToolOfBasic strShortBecomeDate:_theChangeDateStr]]];
   NSLog(@"%@---%@",_theChangeDateStr,_theLastChangeDateStr);
    
}
#pragma mark —————— 一个月有多少行多少列
- (int)numberOfWeekInCurrentMonth:(NSString *)dateStr{
    _lastMonthDaysInOneLine =   [self getLastMonthHaveDaysOfOneWeek:_oneDaysWeekStr];
   int  totalDays = [_theMonthDays intValue] + _lastMonthDaysInOneLine;
//    [self getLastMonthHaveDaysOfOneWeek:_oneDaysWeekStr]//上月占第一行的数量
    int  weeks = 0;
    weeks += totalDays / 7;
    weeks += (totalDays % 7 > 0) ? 1 : 0;
    return weeks;
}
#pragma mark —————— 第一天的星期几来确定 减去第一周的天数
- (NSString *)getWeekDayStr:(NSString *)weekDayStr{
    switch ([weekDayStr intValue]) {
        case 0:
            return @"星期天";
            break;
        case 1:
              return @"星期一";
            break;
        case 2:
              return @"星期二";
            break;
        case 3:
              return @"星期三";
            break;
        case 4:
              return @"星期四";
            break;
        case 5:
              return @"星期五";
            break;
        case 6:
              return @"星期六";
            break;
        case 7:
            return @"星期天";
            break;
            
        default:
            return @"星期";
            break;
    }
}
#pragma mark —————— 上个月在第一行占了多少个小方格
- (int)getLastMonthHaveDaysOfOneWeek:(NSString *)weekDayStr{
    switch ([weekDayStr intValue]) {
        case 0:
            return 6;
            break;
        case 1:
            return 0;
            break;
        case 2:
            return 1;
            break;
        case 3:
            return 2;
            break;
        case 4:
            return 3;
            break;
        case 5:
            return 4;
            break;
        case 6:
            return 5;
            break;
            
        case 7:
            return 6;
            break;
        default:
            return 0;
            break;
    }
}
#pragma mark —————— 日期小块  ⬆️
- (void)addBtns{

    [_dayBackView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    //删去该父视图上面的所有子视图
    int weeks = [self numberOfWeekInCurrentMonth:_theChangeDateStr];
    _calendarCellArr =  [NSMutableArray array];
    //上月
    for (int i = [_lastMonthDays intValue] - _lastMonthDaysInOneLine+1; i < [_lastMonthDays intValue]+1; i ++) {
        [_calendarCellArr addObject:[NSString stringWithFormat:@"%d",i]];
    }
    //这月
   for (int j = 1; j <= [_theMonthDays intValue]; j ++) {
        [_calendarCellArr addObject:[NSString stringWithFormat:@"%d",j]];
    }
    //下月
    for (int q = 1; q <= weeks*7-_lastMonthDaysInOneLine-[_theMonthDays intValue]; q++) {
         [_calendarCellArr addObject:[NSString stringWithFormat:@"%d",q]];
    }
    //宽高
    _dayBackViewLayoutConstraintWidth.constant = Y_mainW;
    if (weeks>5) {
        _dayBackViewLayoutConstraintHeight.constant = Y_mainW*0.715+_kuangao;
 
    }else{
        if (weeks == 4) {
            _dayBackViewLayoutConstraintHeight.constant = Y_mainW*0.715-_kuangao;
        }else{
            _dayBackViewLayoutConstraintHeight.constant = Y_mainW*0.715;
        }
        
    }
    
     NSLog(@"_dayBackViewLayoutConstraint.constant ==%f",_dayBackViewLayoutConstraintHeight.constant );
    for (int i = 0; i < weeks*7; i ++) {
        float a = i % 7;
        float b = i / 7;
        
        UIButton *btnOfCalender = [UIButton buttonWithType:UIButtonTypeCustom];
        btnOfCalender.frame = CGRectMake(a * _kuangao ,b*_kuangao, _kuangao, _kuangao);
        btnOfCalender.layer.borderWidth = 0.3;
        btnOfCalender.layer.borderColor = [[UIColor lightGrayColor]CGColor];
        btnOfCalender.tag = TAG_BTN_B + i;
        [btnOfCalender setTitle:[NSString stringWithFormat:@"%@",_calendarCellArr[i]] forState:UIControlStateNormal];
        [btnOfCalender addTarget:self action:@selector(calendarAction:) forControlEvents:UIControlEventTouchUpInside];
       
        //字体颜色[self getLastMonthHaveDaysOfOneWeek:_oneDaysWeekStr]
        if (i < _lastMonthDaysInOneLine || i >= _lastMonthDaysInOneLine+[_theMonthDays intValue]) {
            //非当前月的日期
            btnOfCalender.userInteractionEnabled = NO;
           [btnOfCalender setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        }else{
            //前月的日期
            NSString *  indexTitle = @"";
            if ([_calendarCellArr[i] intValue]>=10) {
                indexTitle = [NSString stringWithFormat:@"%@",_calendarCellArr[i]];
            }else{
                indexTitle = [NSString stringWithFormat:@"0%@", _calendarCellArr[i]];
            }
            if ([[_theChangeDateStr substringWithRange:NSMakeRange(8, 2)] isEqualToString:indexTitle]) {
                btnOfCalender.selected = YES;
                btnOfCalender.backgroundColor = [UIColor blackColor];
                [btnOfCalender setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                
            }else{
                btnOfCalender.userInteractionEnabled = YES;
                [btnOfCalender setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                btnOfCalender.backgroundColor = [UIColor clearColor];
            }
        }
        //打卡状态
         if (i < _lastMonthDaysInOneLine || i >= _lastMonthDaysInOneLine+[_theMonthDays intValue]) {//非本月
             [btnOfCalender setImage: Y_IMAGE(@"透明圆") forState:UIControlStateNormal];
         }else{
             
//             [self imgOfOneCalender:i-_lastMonthDaysInOneLine];
             [btnOfCalender setImage: [self imgOfOneCalender:i-_lastMonthDaysInOneLine] forState:UIControlStateNormal];
         }

        //颜色标记
        btnOfCalender.titleEdgeInsets = UIEdgeInsetsMake(0,  -btnOfCalender.currentImage.size.width, btnOfCalender.currentImage.size.height, 0);
        btnOfCalender.imageEdgeInsets = UIEdgeInsetsMake(btnOfCalender.titleLabel.intrinsicContentSize.height, 0, 0,  -btnOfCalender.titleLabel.intrinsicContentSize.width);

        [_dayBackView addSubview:btnOfCalender];
    }
}

- (UIImage *)imgOfOneCalender:(int )typeOfTheMonthDay{
    if (_arrOfDaysList.count>typeOfTheMonthDay) {
        
   
       StatisticsOfOneDayModel *model = [StatisticsOfOneDayModel objectWithKeyValues:_arrOfDaysList[typeOfTheMonthDay]];
    
        UIImage *img =  Y_IMAGE(@"正常圆");
        switch ([model.status intValue]) {
                
            case 0:
                img =  Y_IMAGE(@"透明圆");
                break;
                
            case 1:
                img =  Y_IMAGE(@"正常圆");
                break;
                
            case 2:
                  img =  Y_IMAGE(@"外勤圆");
                break;
                
            case 3:
                  img =  Y_IMAGE(@"迟到圆");
                break;
                
            case 4:
                  img =  Y_IMAGE(@"旷工圆");
                break;
                
            case 5:
                  img =  Y_IMAGE(@"请假圆");
                break;
                
            case 6:
                 img =  Y_IMAGE(@"迟到圆");//缺卡状态
                 break;
                
            default:
                  img =  Y_IMAGE(@"透明圆");
                break;
        }
        return img;

    }else{
         UIImage *img =  Y_IMAGE(@"透明圆");
         return img;
    }
    
  }

#pragma mark ——————  calendarAction 某天的点击事件
- (void)calendarAction:(UIButton *)sender{
     NSLog(@"sender.tag=%ld",(long)(sender.tag)-TAG_BTN_B);
    NSInteger i = sender.tag - TAG_BTN_B;
    for (UIButton *btn in   sender.superview.subviews ) {
        //点击的btn
        if ( btn.tag-TAG_BTN_B == i) {
            if (i < _lastMonthDaysInOneLine || i >= _lastMonthDaysInOneLine+[_theMonthDays intValue]) {
                [btn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
            }else{
                [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                if (btn == sender) {
                    btn.selected = YES;
                    btn.backgroundColor = [UIColor blackColor];
                    NSLog(@"-tag-----=%ld==%ld",(long)btn.tag,(long)i);
                    NSLog(@"-title----=%@", _calendarCellArr[i]);
                    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                    [self changeDate:i];
                }
            }
        }else{//非点击的btn
            if (btn.tag-TAG_BTN_B < _lastMonthDaysInOneLine || btn.tag-TAG_BTN_B >= _lastMonthDaysInOneLine+[_theMonthDays intValue]) {
                [btn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
            }else{
                btn.selected = NO;
                btn.backgroundColor = [UIColor clearColor];
                [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            }
        }
    }
}
#pragma mark —————— 点击日期 切换数据
- (void)changeDate:(NSInteger)index{
    
     NSLog(@"点击title＝%@",_calendarCellArr[index]);
    if ([_calendarCellArr[index] intValue]>=10) {//更改当前日期
         _theChangeDateStr = [NSString stringWithFormat:@"%@%@",[_theChangeDateStr substringToIndex:8],_calendarCellArr[index]];//10后
    }else{
        _theChangeDateStr = [NSString stringWithFormat:@"%@0%@",[_theChangeDateStr substringToIndex:8],_calendarCellArr[index]];//单日
    }
   
    [self getDataOfDate:_theChangeDateStr];
    
}
@end
